#!/usr/bin/env python
# $Id: sqluser.py df54dec975f4 2012/09/09 20:22:40 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: df54dec975f4 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-09-09 20:22:40Z $"

import optparse
import sys

from venya.lib import cmdparser
from venya.lib import db
from venya.lib import stdlib

class sqluser(cmdparser.GetOpt):
   option_list = cmdparser.GetOpt.option_list + (
         optparse.make_option("-u", "--user", type = "str",
            help = "SQL Username to add", dest = "user"),
         optparse.make_option("-d", "--database", type = "str",
            help = "SQL database to add", dest = "database"),
         optparse.make_option("-p", "--password", type = "str",
            help = "SQL password for the user", dest = "password"),
         optparse.make_option("-H", "--hostname", type = "str",
            help = "SQL database/username hostname", dest = "hostname"),
         optparse.make_option("-P", type = "str",
            help = "Root user's password", dest = "rootpass"),
         optparse.make_option("-a", "--admin", type = "str",
            help = "MySQL admin username, default: root",
            default = "root", dest = "admin"),
         optparse.make_option("-D", "--dbase", type = "str",
            help = "Admin database to use, default: mysql",
            default = "mysql", dest = "admdb"),
         )

   def __init__(self, **Keywords):
      super(sqluser, self).__init__(**Keywords)
      self._db = None

   def warning(self, Message):
      sys.stdout.write("%s: %s\n" %(str(self), str(Message)))

   def Close(self):
      if self._db:
         self._db.Close()
         self._db = None

   def execute(self, Query):
      retval = None
      try:
         if self._db and Query:
            retval = self._db.Execute(Query)
      except db.SQLError, message:
         self.Close()
         self.error(message)

      return retval

   def handle(self):
      (options, args) = self.parse()

      host = None
      database = None
      rpass = None
      admin = None
      passwd = None
      user = None
      dbase = None

      if options.hostname:
         host = options.hostname.strip()

      if options.admdb:
         database = options.admdb.strip()

      if options.rootpass:
         rpass = options.rootpass.strip()

      if options.admin:
         admin = options.admin.strip()

      if options.password:
         passwd = options.password.strip()
      else:
         passwd = stdlib.GetRandomString(15).strip()

      if options.user:
         username = options.user.strip()
      else:
         self.error("no username defined!")

      if options.database:
         dbase = options.database.strip()
      else:
         self.error("no database defined!")

      self._db = db.mysql(database, host, admin, rpass)

      query = "create database if not exists %s;" %dbase
      self.execute(query)

      query = "create user '%s'@'localhost' identified by '%s';" %(
            username, passwd)
      self.execute(query)

      query = "create user '%s'@'%%' identified by '%s';" %(username, passwd)
      self.execute(query)

      query = "GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' " %(
            dbase, username)
      query += "WITH GRANT OPTION; "
      self.execute(query)

      query = "GRANT ALL PRIVILEGES ON %s.* TO '%s'@'%%' " %(
            dbase, username)
      query += "WITH GRANT OPTION; "
      self.execute(query)

      query = "flush privileges;"
      self.execute(query)

      self.Close()
      print "Username: %s, password: %s" %(username, passwd)

if __name__ == "__main__":
   sqlopt = sqluser(version = 1.2, args = sys.argv)
   if len(sqlopt) <= 1:
      sqlopt.printhelp()
   else:
      try:
         sqlopt.handle()
      except cmdparser.GetOptError, message:
         print message
         sys.exit(1)
